<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateCarAuthAPIRequest;
use App\Http\Requests\API\CreateCarAuthLogAPIRequest;
use App\Http\Requests\API\UpdateCarAuthAPIRequest;
use App\Http\Requests\API\UpdateCarAuthLogAPIRequest;
use App\Models\Store;
use App\Models\CarAuth;
use App\Models\CarAuthLog;
use App\Models\ParkInfo;
use App\Models\SellIssues;
use App\Repositories\CarAuthRepository;
use App\Repositories\CarAuthLogRepository;
use App\Services\AuthServices;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Client;
use Illuminate\Log;
use Response;
use Excel;
use Illuminate\Support\Facades\Storage;
use InfyOm\Generator\Utils\ResponseUtil;


/**
 * Class CarAuthController
 * @package App\Http\Controllers\API
 */

class CarAuthAPIController extends AppBaseController
{
    use AuthServices;
    /** @var  CarAuthRepository */
    private $carAuthRepository;
    private $carAuthLogRepository;
    private $status = [0=>'下发中',1=>'下发成功',2=>'下发失败',];

    protected function newHttp()
    {
        return new Client([
            'base_uri'=>config('custom.car_auth_api_url'),
        ]);
    }

    public function __construct(CarAuthRepository $carAuthRepo,CarAuthLogRepository $carAuthLogRepo)
    {
        $this->carAuthRepository = $carAuthRepo;
        $this->carAuthLogRepository = $carAuthLogRepo;
    }

    /**
     * Display a listing of the CarAuth.
     * GET|HEAD /carAuths
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $where = [];
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;
        $date = date("Y-m-d H:i:s");

        //$idRes = CarAuth::select(["vpl_number","id"])
                        //->whereIn("park_code", $input['park_code'])
        //                ->distinct("vpl_number")->get()->groupBy("vpl_number")->toArray();

        $idRes = CarAuth::select(["vpl_number","id"]);
        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $idRes = $idRes->whereIn("park_code", $input['park_code']);
        }
        if(isset($input['username']) && $input['username']){
            $idRes = $idRes->where('username','like','%'.$input['username'].'%');
        }
        if(isset($input['vpl_number']) && $input['vpl_number']){
            $idRes = $idRes->where('vpl_number','like','%'.strtoupper($input['vpl_number']).'%');
        }
        if(isset($input['type']) && is_numeric($input['type'])){
            $idRes = $idRes->where('type',$input['type']);
        }
        $idRes =  $idRes->distinct("vpl_number")
            ->get()->groupBy("vpl_number")->toArray();

        $ids = [];
        foreach ($idRes as $val) {
            $ids[] = $val[0]['id'];
        }
        $this->log("ids count is :".count($ids));
        $m = CarAuth::select("carauths.*");
        if(isset($input['username']) && $input['username']){
            $where[] = ['username','like','%'.$input['username'].'%'];
        }
        if(isset($input['vpl_number']) && $input['vpl_number']){
            $where[] = ['vpl_number','like','%'.strtoupper($input['vpl_number']).'%'];
        }
        if(isset($input['type']) && is_numeric($input['type'])){
            $where['type'] = $input['type'];
        }
        if(isset($input['issued_status']) && is_numeric($input['issued_status'])){
            $where['issued_status'] = $input['issued_status'];
        }
        if(isset($input['belong_org']) && is_numeric($input['belong_org'])){
            $where['belong_org'] = $input['belong_org'];
        }
        if(isset($input['is_valid']) && is_numeric($input['is_valid'])){
            if($input['is_valid'] == 2 ){  //   过期
                $where[] = ['validetime','<=',$date];
            } else if($input['is_valid'] == 1 ){  // 没有过期
                $where[] = ['validetime','>',$date];
            }
        }
        if(isset($input['vtime']) && !empty($input['vtime'])){
            if($input['vtime'][0]){  //   未过期
                $where[] = ['validbtime','>=',$input['vtime'][0]];
            }
            if($input['vtime'][1] ){  // 已过期
                $where[] = ['validetime','<=',$input['vtime'][1]];
            }
        }

        if(!empty($where)){
            $m = $m->where($where);
        }
        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            foreach ($input['park_code'] as &$val) {
                $val = (string)$val;
            }
            $m = $m->whereIn("park_code", $input['park_code']);
        }
        $m =  $m->with('organization')->with(['operators'=>function($query){
            $query->select('id','true_name','name','phone','email');
        }]);
        $m = $m->leftJoin('users','users.id','=','carauths.operator_id');
        if(isset($input['operator']) && $input['operator']){
            $m = $m->where('users.true_name','like','%'.$input['operator'].'%');
        }
        $carAuths = $m->whereIn("carauths.id",$ids)->orderBy("id",'desc')->paginate($pages, array("*"), "page", $page);
        foreach ($carAuths as &$val) {
            if(($val->validetime >= $date)){
                $val->is_valid = '否';
            } elseif($val->validbtime >= $date) {
                $val->is_valid = '否';
            } elseif($val->validetime <= $date){
                $val->is_valid = '是';
            }
            $val['status_name'] = isset($this->status[$val->issued_status])?$this->status[$val->issued_status]:'下发失败';
            $tmp_img = explode(",",$val->images);
            $img_arr = [];
            foreach ($tmp_img as $v) {
                $v =  $v?config('custom.file_visit_url').'/'.$v:'';
                if($v) {
                    $img_arr[] = $v;
                }
            }
            $val->img_arr = $img_arr;
            $park_name = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
            $val->park_name = $park_name?$park_name:'';
            $val->vpl_number_arr = explode(",",$val->vpl_number);
            $tmpList = CarAuth::where("vpl_number", "like", '%'.$val->vpl_number.'%')->get();
            foreach ($tmpList as &$v) {
                if(($v->validetime >= $date)){
                    $v->is_valid = '否';
                } elseif($v->validbtime >= $date) {
                    $v->is_valid = '否';
                } elseif($v->validetime <= $date){
                    $v->is_valid = '是';
                }
                $v['status_name'] = isset($this->status[$v->issued_status])?$this->status[$v->issued_status]:'下发失败';
                $tmp_img = explode(",",$v->images);
                $img_arr = [];
                foreach ($tmp_img as $vv) {
                    $vm =  $vv?config('custom.file_visit_url').'/'.$vv:'';
                    if($v) {
                        $img_arr[] = $vm;
                    }
                }
                $v->img_arr = $img_arr;
                $park_name = ParkInfo::where("park_code",$v->park_code)->value("parking_name");
                $v->park_name = $park_name?$park_name:'';
                $v->vpl_number_arr = explode(",",$v->vpl_number);
            }
            $val->list = $tmpList;
        }
//        $data = $carAuths->toArray();
//        $carAuths = collect($data['data'])->groupBy("vpl_number");
//        $data['data'] = $carAuths;
        return $this->sendResponse($carAuths->toArray(), '授权列表获取成功');
    }



    /**
     * Display a listing of the CarAuth.
     * GET|HEAD /carAuths
     *
     * @param Request $request
     * @return Response
     */
    public function logList(Request $request)
    {
        $where = [];
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;

        $m = CarAuthLog::select("carauths_log.*");
        if(isset($input['username']) && $input['username']){
            $where[] = ['username','like','%'.$input['username'].'%'];
        }
        if(isset($input['vpl_number']) && $input['vpl_number']){
            $where[] = ['vpl_number','like','%'.strtoupper($input['vpl_number']).'%'];
        }
        if(isset($input['type']) && is_numeric($input['type'])){
            $where['type'] = $input['type'];
        }
        if(isset($input['issued_status']) && is_numeric($input['issued_status'])){
            $where['issued_status'] = $input['issued_status'];
        }
        if(isset($input['belong_org']) && is_numeric($input['belong_org'])){
            $where['belong_org'] = $input['belong_org'];
        }
        if(isset($input['is_valid']) && is_numeric($input['is_valid'])){
            if($input['is_valid'] == 1 ){  //   未过期
                $where[] = ['validetime','<=',date("Y-m-d H:i:s")];
            } else if($input['is_valid'] == 2 ){  // 已过期
                $where[] = ['validetime','>',date("Y-m-d H:i:s")];
            }
        }
        if(isset($input['vtime']) && !empty($input['vtime'])){
            if($input['vtime'][0]){  //   未过期
                $where[] = ['validbtime','>=',$input['vtime'][0]];
            }
            if($input['vtime'][1] ){  // 已过期
                $where[] = ['validetime','<=',$input['vtime'][1]];
            }
        }

        if(!empty($where)){
            $m = $m->where($where);
        }
        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            foreach ($input['park_code'] as &$val) {
                $val = (string)$val;
            }
            $m = $m->whereIn("park_code", $input['park_code']);
        }
        $m =  $m->with('organization')->with(['operators'=>function($query){
            $query->select('id','true_name','name','phone','email');
        }]);
        $m = $m->leftJoin('users','users.id','=','carauths_log.operator_id');
        if(isset($input['operator']) && $input['operator']){
            $m = $m->where('users.true_name','like','%'.$input['operator'].'%');
        }
        $carAuths = $m->orderBy("id","desc")->paginate($pages, array("*"), "page", $page);
        $date = date("Y-m-d H:i:s");
        foreach ($carAuths as &$val) {
            if(($val->validbtime <= $date && $val->validetime >= $date)){
                $val->is_valid = '否';
            } elseif($val->validbtime >= $date) {
                $val->is_valid = '是';
            } elseif($val->validetime <= $date){
                $val->is_valid = '是';

            }
            $val['status'] = isset($this->status[$val->issued_status])?$this->status[$val->issued_status]:'';
            $tmp_img = explode(",",$val->images);
            $img_arr = [];
            foreach ($tmp_img as $v) {
                $v =  $v?config('custom.file_visit_url').'/'.$v:'';
                if($v) {
                    $img_arr[] = $v;
                }
            }
            $val->img_arr = $img_arr;
            $park_name = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
            $val->park_name = $park_name?$park_name:'';
            $val->vpl_number_arr = explode(",",$val->vpl_number);
        }
        return $this->sendResponse($carAuths->toArray(), '授权列表获取成功');
    }

    /**
     * Save a newly created CarAuth in storage.
     * POST /carAuths
     *
     * @param CreateCarAuthAPIRequest $request
     *
     * @return Response
     */
    public function save(Request $request)
    {
        $status = $request->input('status',1);
        $this->log('开始回调自由接口，添加授权记录'.$request->input('serial_no').', status : '.$status);
        // 添加操作日志
        $carAuths = $this->carAuthLogRepository
            ->scopeQuery(function($query){
                return $query->orderBy('id','desc');
            })
            ->findWhere(['serial_no'=>$request->input('serial_no')])
            ->first();

        if(empty($carAuths->id)){
            $this->log('数据为空');
            return $this->sendError('数据为空');
        }
        $this->carAuthLogRepository->update(['issued_status'=>($status==0?1:2)],$carAuths->id);
        $this->log('开始获取数据');
        $carAuths = obj2arr($carAuths);
        $this->log(json_encode($carAuths));
        $res = '';
        if($carAuths['option'] == 'add' && $status == 0) {
            $this->log('添加获取数据--add');
            unset($carAuths['id']);
            unset($carAuths['organization']);
            unset($carAuths['organizations']);
            $addcarAuths = $this->carAuthRepository
                ->findWhere(['serial_no'=>$request->input('serial_no')])
                ->first();
            if(!empty($addcarAuths)) return $this->sendResponse([], '数据已经添加');
            $carAuths['issued_status'] = 1;
            $this->log('add data --'.json_encode($carAuths));
            $res = $this->carAuthRepository->create($carAuths);
        } else if($carAuths['option'] == 'edit' && $status == 0) {
            $this->log('编辑数据--edit');
            $tmp_car = $this->carAuthRepository
                ->findWhere(['serial_no'=>$request->input('serial_no')])
                ->first();
            unset($carAuths['organization']);
            unset($carAuths['organizations']);
            $carAuths['issued_status'] = 1;
            $res = $this->carAuthRepository->update($carAuths,$tmp_car['id']);
        } else if($carAuths['option'] == 'delete' && $status == 0) {
            $this->log('删除数据--delete');
            $tmp_car = $this->carAuthRepository
                ->findWhere(['serial_no'=>$request->input('serial_no')])
                ->first();
            $this->log($tmp_car['id']);
            $res = $this->carAuthRepository->delete($tmp_car['id']);
        } else if($carAuths['option'] == 'store_add' && $status == 0) {
            $this->log('添加预售--store_add');
            $tmp_car = SellIssues::where(['serial_no'=>$request->input('serial_no')])
                ->first();
            $this->log($tmp_car['id']);
            $carAuths = [];
            $carAuths['status'] = 3;
            $res = SellIssues::where("id",$tmp_car['id'])->update($carAuths);
            (isset($tmp_car['store_id']) && !empty($tmp_car['store_id']))?Store::where('id',$tmp_car['store_id'])->update(['vpl_status'=>4]):'';
        } else if($carAuths['option'] == 'store_edit' && $status == 0) {
            $this->log('修改预售--store_edit');
            $tmp_car = SellIssues::where(['serial_no'=>$request->input('serial_no')])
                ->first();
            $this->log($tmp_car['id']);
            $carAuths = [];
            $carAuths['status'] = 3;
            $res = SellIssues::where("id",$tmp_car['id'])->update($carAuths);
            (isset($tmp_car['store_id']) && !empty($tmp_car['store_id']))?Store::where('id',$tmp_car['store_id'])->update(['vpl_status'=>4]):'';
        } else if($carAuths['option'] == 'store_delete' && $status == 0) {
            $this->log('删除预售--store_delete');
            $tmp_car = SellIssues::where(['serial_no'=>$request->input('serial_no')])
                ->first();
            $this->log($tmp_car['id']);
            $res = SellIssues::delete($tmp_car['id']);
            (isset($tmp_car['store_id']) && !empty($tmp_car['store_id']))?Store::where('id',$tmp_car['store_id'])->update(['vpl_status'=>4]):'';
        }
        if(!$res) {
            $this->log('保存失败');
            return $this->sendError('保存失败');
        }
        $this->log('调用结束，成功添加授权记录');
        return $this->sendResponse([], '授权车辆存成功');
    }

    /**
     * Store a newly created CarAuth in storage.
     * POST /carAuths
     *
     * @param CreateCarAuthAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateCarAuthLogAPIRequest $request)
    {
        $input = $request->all();
        $user = Auth::user();
        $user = obj2arr($user);
        $input['operator_id'] = $user['id'];
        $input['operator'] = $user['true_name'];
        $input['email'] = $user['email'];
        $input['mobile'] = $input['phone']??'';
        $input['share'] = (isset($input['share_count']) && !empty($input['share_count']))?1:0;;
        $input['priority'] = 2;
        $input['images'] = $input['image']??'';
        unset($input['image']);

        $existAuths = [];
        foreach ($input['park_code'] as $val) {
            
            $isExist = false;
            // 同一车场 车辆 一个时间段里只有一次
            foreach ($input['vpl_number'] as $v) {
                $repeatRes = $carAuths = $this->carAuthRepository->findWhere([
                    "park_code"=>$val,
                    ["vpl_number",'like','%'.$v."%"],
                    ['validbtime','<=',$input['validbtime']],
                    ['validetime','>=',$input['validbtime']]
                ])->all(["id"]);
                if(obj2arr($repeatRes)){
                    $isExist = true;
                    $existAuths[] = $v;
                    continue;
                }
                $repeatRes = $carAuths = $this->carAuthRepository->findWhere([
                    "park_code"=>$val,
                    ["vpl_number",'like','%'.$v."%"],
                    ['validbtime','<',$input['validetime']],
                    ['validetime','>',$input['validetime']]
                ])->all("id");
                if(obj2arr($repeatRes)){
                    $isExist = true;
                    $existAuths[] = $v;
                    continue;
                }
            }

            // 已存在重复授权
            if ($isExist){
                continue;
            }

            $data = $input;
            unset($data['park_code']);
            $data['park_code'] = $val;
            $data['vpl_number'] = implode(",", $input['vpl_number']);
            $data['cardno'] = md5(time().rand(0,9));
            $data['serial_no'] = md5(time().rand(0,9));
            $data['option'] = 'add';
            $carAuths = $this->carAuthLogRepository->create($data);
            $data['validbtime'] = strtotime($input['validbtime']);
            $data['validetime'] = strtotime($input['validetime']);

            if($carAuths) {
                $number_str = '[';
                foreach ($input['vpl_number'] as $item) {
                    $number_str .=  '["'.$item.'",""],';
                }
                $data['vpl_number'] = trim($number_str,',').']';
                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if($res['code'] == 0) {
                    $this->carAuthLogRepository->update(['issued_status' => 0], $carAuths->id);
                } else {
                    $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                }
            }
        }
        return $this->sendResponse($existAuths, '正在下发授权中......');
    }

    /**
     * 批量下发车辆授权
     *
     * @param Request $request
     */
    public function massAuth(Request $request){
        set_time_limit(0);
        $filePath = storage_path().'/app/uploads/'.$request->input('file');
        if(!file_exists($filePath)){
            return $this->sendError('文件不存在');
        }
        $park_code = $request->input('park_code');
        $auth_type = config('custom.auth_type');
        $auth_type = array_flip($auth_type);
        Excel::load($filePath, function($reader) use($filePath,$park_code,$auth_type){
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
            // 0 车牌号  1共享车位 2 授权类型  3 起始时间 4 结束日期 5 电话 6 所属机构
            unset($res[0]); // 注销文件首行

            $carAuths = [];
            $auth_num = 0;
            foreach ($res as $re) {
                if(empty($re[1])) continue;
                // 同一车场 车辆 一个时间段里只有一次
                $vpl_numbers = explode(",",$re[1]);
                foreach ($vpl_numbers as $v) {
                    $repeatRes = $carAuths = $this->carAuthRepository->findWhere([
                        "park_code"=>$park_code,
                        ["vpl_number",'like','%'.$v."%"],
                        ['validbtime','<=',$re[4]],
                        ['validetime','>=',$re[5]]
                    ])->all(["id"]);
                    if(obj2arr($repeatRes)){
                        $r = [
                            'success'=>false,
                            'data'=>[],
                            'message'=>'已存在的'.$v.'此车辆授权时间段有重叠,请修正您的excel数据',
                        ];
                        exit(json_encode($r));
                    }
                    $repeatRes = $carAuths = $this->carAuthRepository->findWhere([
                        "park_code"=>$park_code,
                        ["vpl_number",'like','%'.$v."%"],
                        ['validbtime','<',$re[4]],
                        ['validetime','>',$re[5]]
                    ])->all("id");
                    if(obj2arr($repeatRes)){
                        $r = [
                            'success'=>false,
                            'data'=>[],
                            'message'=>'已存在的'.$v.'此车辆授权时间段有重叠,请修正您的excel数据',
                        ];
                        exit(json_encode($r));
                    }
                }

                $data = [];
                unset($data['park_code']);
                if(!isset($auth_type[$re['3']])) continue;
                $data['park_code'] = $park_code;
                $data['type'] = $auth_type[$re['3']];
                $data['share'] = $re['2'];
                $data['share_count'] = $re['2'];
                $data['mobile'] = $re['6'];
                $data['username'] = $re[0];
//                $data['belong_org'] = '';
                $data['priority'] = 2;
                $data['vpl_number'] = implode(",", $vpl_numbers);
                $data['cardno'] = md5(time().rand(0,9));
                $data['serial_no'] = md5(time().rand(0,9));
                $data['option'] = 'add';
                $data['validbtime'] = date("Y-m-d H:i:s",strtotime($re[4]));
                $data['validetime'] = date("Y-m-d H:i:s",strtotime($re[5]));
                $carAuths = $this->carAuthLogRepository->create($data);
                $data['validbtime'] = strtotime($re[4]);
                $data['validetime'] = strtotime($re[5]);

                if($carAuths) {
                    $number_str = '[';
                    foreach ($vpl_numbers as $item) {
                        if(!empty($item)) {
                            $number_str .= '["' . $item . '",""],';
                        }
                    }
                    $data['vpl_number'] = trim($number_str,',').']';
                    // 查看返回状态
                    $this->log('开始传递 CAR data');
                    $this->log('参数数据:'.json_encode($data));
                    $res = $this->sendAuthData($data);
                    $auth_num++;
                    if($auth_num == 200){
                        sleep(5);
                        $auth_num = 0;
                    }
                    $this->log('返回参数：'.json_encode($res));
                    if($res['code'] == 0) {
                        $this->carAuthLogRepository->update(['issued_status' => 0], $carAuths->id);
                    } else {
                        $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                    }
                }
                sleep(1);

            }
            if(file_exists($filePath)) unlink($filePath);
            $r = [
                'success'=>true,
                'data'=>isset($carAuths)?$carAuths->toArray():[],
                'message'=>'正在下发授权中......',
            ];
            exit(json_encode($r));
        });

        return $this->sendError('无效文件');
    }

    /**
     * 批量下发车辆授权
     *
     * @param Request $request
     */
    public function massFile(Request $request){
        $file = $request->file('file');
        // 文件是否上传成功
        if ($file->isValid()) {
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            $filename =  time().'.' . $ext;
            $filePath = storage_path().'/app/uploads/'.$filename;
            // 使用我们新建的uploads本地存储空间（目录）
            //这里的uploads是配置文件的名称
            $bool = Storage::disk('uploads')->put($filename, fopen($request->file('file')->getRealPath(), 'r'));
            if(!file_exists($filePath)){
                return $this->sendError('上传失败');
            }
            if($bool){
                $auth_type = config('custom.auth_type');
                $auth_type = array_flip($auth_type);
                Excel::load($filePath, function($reader) use($filePath,$auth_type){
                    $reader = $reader->getSheet(0);
                    $res = $reader->toArray();
                    // 0 车牌号  1共享车位 2 授权类型  3 起始时间 4 结束日期 5 电话 6 所属机构
                    unset($res[0]); // 注销文件首行
                    foreach ($res as $re) {
                        if(empty($re[1])) continue;
                        //判断时间格式
                        if(strtotime($re['4']) == '' || strtotime($re['5']) == ''){
                            $r = [
                                'success'=>false,
                                'data'=>[],
                                'message'=>'文件授权时间格式有问题！',
                            ];
                            exit(json_encode($r));
                        }

                        if(!is_numeric($re[2])){
                            $r = [
                                'success'=>false,
                                'data'=>[],
                                'message'=>'共享车位数有问题！',
                            ];
                            exit(json_encode($r));
                        }
                        if(!isset($auth_type[$re['3']])) {
                            $r = [
                                'success'=>false,
                                'data'=>[],
                                'message'=>'有不存在的授权类型:'.$re['3'],
                            ];
                            exit(json_encode($r));
                        }
                        // 同一车场 车辆 一个时间段里只有一次
                        $vpl_numbers = explode(",",$re[1]);
//                        foreach ($vpl_numbers as $v) {
//                            $repeatRes = $carAuths = $this->carAuthRepository->findWhere([
//                                "park_code"=>$park_code,
//                                ["vpl_number",'like','%'.$v."%"],
//                                ['validbtime','<=',$re[3]],
//                                ['validetime','>=',$re[4]]
//                            ])->all(["id"]);
//                            if(obj2arr($repeatRes)){
//                                $r = [
//                                    'success'=>true,
//                                    'data'=>[],
//                                    'message'=>'已存在的此车辆授权时间段有重叠！',
//                                ];
//                                exit(json_encode($r));
//                            }
//                            $repeatRes = $carAuths = $this->carAuthRepository->findWhere([
//                                "park_code"=>$park_code,
//                                ["vpl_number",'like','%'.$v."%"],
//                                ['validbtime','<',$re[3]],
//                                ['validetime','>',$re[4]]
//                            ])->all("id");
//                            if(obj2arr($repeatRes)){
//                                $r = [
//                                    'success'=>true,
//                                    'data'=>[],
//                                    'message'=>'已存在的此车辆授权时间段有重叠！',
//                                ];
//                                exit(json_encode($r));
//                            }
//                        }
                    }

                });
                return $this->sendResponse($filename, '上传成功');
            }
            return $this->sendError('上传失败');
        }
        return $this->sendError('无效文件');
    }

    private function editCarData($data){
        $res = curl_post(config('custom.car_auth_api_url')."/auth_group_edit?src=airport",$data);
        return $res;
    }
    /**
     * Display the specified CarAuth.
     * GET|HEAD /carAuths/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var CarAuth $carAuth */
        $carAuth = $this->carAuthRepository->findWithoutFail($id);

        if (empty($carAuth)) {
            return $this->sendError('查询失败');
        }
        $res = $carAuth->toArray();
        $date = date("Y-m-d H:i:s");
        if(($res['validbtime'] <= $date && $res['validetime'] >= $date)){
            $res['is_valid'] = '否';
        } elseif($res['validbtime'] >= $date) {
            $val['is_valid'] = '是';
        } elseif($res['validetime'] <= $date){
            $res['is_valid'] = '是';
        }
        $tmp_img = explode(",",$res['images']);
        foreach ($tmp_img as &$v) {
            $v = config('custom.file_upload_url').$v;
        }
        $res['img_arr'] = $tmp_img;
        return $this->sendResponse($res, '授权查询成功');
    }

    /**
     * Update the specified CarAuth in storage.
     * PUT/PATCH /carAuths/{id}
     *
     * @param  int $id
     * @param UpdateCarAuthAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateCarAuthAPIRequest $request)
    {
        $input = $request->all();
        /** @var CarAuth $carAuth */
        $carAuth = $this->carAuthRepository->findWithoutFail($id);

        if (empty($carAuth)) {
            return $this->sendError('操作失败');
        }
        $user = Auth::user();
        $user = obj2arr($user);
        $input['cardno'] = $carAuth->cardno;
        $input['serial_no'] = $carAuth->serial_no;
        $input['operator'] = $user['true_name'];
        $input['email'] = $user['email'];
        $input['mobile'] = $input['phone']??'';
        $input['share'] = '1';
        $input['share_count'] = 1;
        $input['priority'] = 2;

        foreach ($input['park_code'] as $val) {
            foreach ($input['vpl_number'] as $v) {
                // 同一车场 车辆 一个时间段里只有一次
                $repeatRes = $this->carAuthRepository->findWhere([
                    "park_code" => $val,
                    ["vpl_number",'like',$v.","],
                    ['validbtime', '<=', $input['validbtime']],
                    ['validetime', '>=', $input['validbtime']],
                    ['id', '<>', $id],
                ])->all();
                if (obj2arr($repeatRes)) {
                    return $this->sendError('已存在的此车辆授权开始时间段重叠');
                }
                $repeatRes = $this->carAuthRepository->findWhere([
                    "park_code" => $val,
                    ["vpl_number",'like',$v.","],
                    ['validbtime', '<', $input['validetime']],
                    ['validetime', '>', $input['validetime']],
                    ['id', '<>', $id],
                ])->all();
                if (obj2arr($repeatRes)) {
                    return $this->sendError('已存在的此车辆授权结束时间段重叠');
                }
            }
            $data = $input;
            unset($data['park_code']);
            $data['park_code'] = $val;
            $data['vpl_number'] = implode(",", $input['vpl_number']);
            $data['option'] = 'edit';
            $carAuthlogs = $this->carAuthLogRepository->create($data);
//            $carAuths = $this->carAuthRepository->update($data,$id);
            unset($data['park_code']);
            $number_str = '[';
            foreach ($input['vpl_number'] as $item) {
                $number_str .=  '["'.$item.'",""]';
            }
            $number_str = $number_str.']';
//            $tmp['auth_no'] = $carAuth->serial_no;
            $tmp['park_code'] = $val;
            $tmp['cardno'] = $carAuth->cardno;
            $tmp['serial_no'] = $carAuth->serial_no;
            $tmp['edit_map'] = json_encode([
//                'auth_type'=>$input['type'],
                'share_tol'=>$input['share_count'],
                'holder_name'=>$input['operator'],
                'validity_start'=>strtotime($input['validbtime']),
                'validity_end'=>strtotime($input['validetime']),
                'is_share'=>($input['share_count']>0 || empty($input['share_count']))?1:0,
                'phone'=>$input['mobile'],
                'email'=>$input['email'],
//                'plate_list'=>$number_str,
            ]);
            $tmp['operator'] = $user['true_name'];
            $tmp['edit_time'] = time();
            // 查看返回状态
            $this->log('开始传递 CAR data');
            $this->log('参数数据:'.json_encode($tmp));
            $res = $this->editCarData($tmp);
            $this->log('返回参数：'.($res));
            $res = json_decode($res,true);
            if($res['code'] == 0){
                $this->carAuthLogRepository->update(['issued_status'=>1],$id);
            } else {
                if($carAuthlogs) {
                    $this->carAuthLogRepository->update(['issued_status' => 2], $carAuthlogs->id);
                }
            }
        }
        return $this->sendResponse($carAuth->toArray(), '正在授权更新中.....');
    }

    /**
     * Remove the specified CarAuth from storage.
     * DELETE /carAuths/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var CarAuth $carAuth */
        $carAuth = $this->carAuthRepository->findWithoutFail($id);
        if (empty($carAuth)) {
            return $this->sendError('没有此授权');
        }
        $carAuth = obj2arr($carAuth);
        unset($carAuth['id']);
        $carAuth['option'] = 'delete';
        unset($carAuth['created_at']);
        unset($carAuth['updated_at']);
        unset($carAuth['organization']);
        unset($carAuth['organizations']);
        $this->carAuthLogRepository->create($carAuth);
        $data = [
            'serial_no'=>$carAuth['serial_no'],
            'cardno'=>$carAuth['cardno'],
            'park_code'=>$carAuth['park_code']
        ];
        $res = $this->deleteAuth($data);
        $this->log(json_encode($res));
        if($res['code'] == 0){
            return $this->sendResponse($id, '正在删除授权中.....');
        }
        return $this->sendError('授权删除失败');
    }
}
